package vip.websky.project.web;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import vip.websky.project.common.config.SysConst;

/**
 * @Author Yong.Yang E-mail:yang2048@qq.com
 * @Create 2017/8/27-17:39
 **/
@Slf4j
public class HttpRequestUtils {
    private final static String URL = "http://localhost:8080/common/interface";

    /**
     * HTTP 发送post请求
     */
    public static String doPost(GetRequestDTO requestDTO){
        log.info("请求参数:{}",requestDTO);
        HttpPost post = new HttpPost(URL);
        String result="";
        try {
            StringEntity se = new StringEntity(JSON.toJSONString(requestDTO), SysConst.SYS_CHARSET);
            se.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(se);
            HttpResponse httpResponse = HttpClients.createDefault().execute(post);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(httpResponse.getEntity(), SysConst.SYS_CHARSET);// 返回json格式：
                log.info("返回:{}",result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
